// import {constants as constants} from '../utils/constants.js'
import {getStorage, putStorage, getCookies, setCookies} from '../utils/storage'
import crypto from '../utils/crypto.js'

const constants = require('../utils/constants.js').default;

/**
 * 判断用户是否处于登录状态
 */
export function isLogin() {
  let loginStatus = getCookies(constants.loginStatus);
  return !!loginStatus;
}

/**
 * 判断用户以前是否登录
 * @returns {string}
 */
export function isLoginBefore() {
  return getStorage(constants.storageKeys.LOGIN_PUB);
}

/**
 * 用户登录
 * @param secret 密码
 * result true:登录成功  false:登录失败
 */
export function login(secret) {
  let oldSecretPub = getStorage(constants.storageKeys.LOGIN_PUB);
  let pubKey = crypto.getPrivateAndPublicKeyFromSecret(secret).publicKey;
  if (oldSecretPub && pubKey && oldSecretPub === pubKey) {
    setCookies(constants.loginStatus, true);
    return true;
  } else {
    return false;
  }
}

/**
 * 注册
 * @param secret
 */
export function register(secret) {
  try {
    let pubKey = crypto.getPrivateAndPublicKeyFromSecret(secret).publicKey;
    putStorage(constants.storageKeys.LOGIN_PUB, pubKey);
    return true;
  } catch (e) {
    console.log('register error!')
  }
}
